package com.wanfajie.smsdistribute.util

import android.content.Context
import android.os.Build
import android.os.Parcel
import android.os.Parcelable
import android.telephony.SubscriptionManager
import android.telephony.TelephonyManager
import android.view.Gravity
import android.view.View
import android.widget.PopupMenu
import com.wanfajie.smsdistribute.MyApplication
import com.wanfajie.smsdistribute.R

private val subManager: SubscriptionManager? by lazy {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        MyApplication.appContext.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager
    } else {
        null
    }
}

private val telManager: TelephonyManager by lazy {
    MyApplication.appContext.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
}

data class SimCardInfo(
        val name: String,
        val carrierName: String,
        val number: String,
        val slotIndex: Int,
        val enable: Boolean
) : Parcelable {

    constructor(parcel: Parcel) : this(
            parcel.readString(),
            parcel.readString(),
            parcel.readString(),
            parcel.readInt(),
            parcel.readByte() != 0.toByte()
    )

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(name)
        parcel.writeString(carrierName)
        parcel.writeString(number)
        parcel.writeInt(slotIndex)
        parcel.writeByte(if (enable) 1 else 0)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<SimCardInfo> {
        override fun createFromParcel(parcel: Parcel): SimCardInfo {
            return SimCardInfo(parcel)
        }

        override fun newArray(size: Int): Array<SimCardInfo?> {
            return arrayOfNulls(size)
        }
    }

}

fun getSimInfoList(): List<SimCardInfo> {
    val result = ArrayList<SimCardInfo>()
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        subManager!!.activeSubscriptionInfoList.forEach {
            result.add(SimCardInfo(it.displayName.toString(),
                    it.carrierName.toString(),
                    it.number ?: "",
                    it.simSlotIndex, true)
            )
        }
    } else if (telManager.simState == TelephonyManager.SIM_STATE_READY) {
        // XXX: 我知道这一段不好使...

        val number = try {
            telManager.line1Number
        } catch (e: SecurityException) {
            ""
        }

        val networkOperaName = telManager.networkOperatorName ?: ""
        if (networkOperaName.isNotEmpty()) {
            val info = SimCardInfo("",
                telManager.networkOperatorName,
                number,
                0,
                telManager.simState == TelephonyManager.SIM_STATE_READY
            )

            result.add(info)
        }
    }

    println("networkOperator: ${telManager.networkOperator}\nsimop: ${telManager.simOperator}\nsimopName: ${telManager.simOperatorName}")

    return result.sortedBy { it.slotIndex }
}

fun selectCard(ctx: Context, anchor: View, gravity: Int = Gravity.END, cb: (SimCardInfo) -> Unit) {
    val popup = PopupMenu(ctx, anchor)
    val infos = getSimInfoList()
    val items = infos.map {
        popup.menu.add("${it.slotIndex+1} ${it.carrierName}${it.number}")
    }

    if (items.isNotEmpty()) {
        popup.setOnMenuItemClickListener {
            val i = items.indexOf(it)

            cb(infos[i])
            true
        }
    } else {
        popup.menu.add(R.string.empty).apply {
            isEnabled = false
            isCheckable = false
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            popup.gravity = gravity
        }
    }

    popup.show()
}
